package com.zm.demo.oauth2.client;

import com.alibaba.fastjson.JSONObject;
import com.zm.demo.oauth2.client.util.OkHttpUtil;
import okhttp3.Response;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class OAuthOscChinaController {
    private String clientId="Tgz0hDwzvXyrH1t59Pb2";
    private String clientSecret="qBWLFayPXxhMj1eEBLrm47I0yobyd7ZB";

    @RequestMapping("/oauth/redirect")
    public String redirect(String code) throws Exception{

        StringBuilder url = new StringBuilder("https://www.oschina.net/action/oauth2/authorize?");
        url.append("client_id=").append(clientId);
        url.append("&client_secret=").append(clientSecret);
        url.append("&code=").append(code);
        url.append("&grant_type=authorization_code");
        url.append("redirect_uri=").append("http%3A%2F%2Flocalhost%3A8080%2Foauthtest%2Fcallback");
        System.out.println(code);
        Response response = OkHttpUtil.post(url.toString(), "application/json", null);
        String result = new String(response.body().bytes());
        System.out.println(result);
        return result;
    }

    @RequestMapping("/oauth/redirect1")
    public String redirect1(@org.springframework.web.bind.annotation.RequestBody JSONObject jsonObject){
        System.out.println(jsonObject.toJSONString());
        return "";
    }

    @RequestMapping("/oauth/user")
    public String user(String token) throws Exception{
        //access_token=e6a7cc037b9a436cea9c39cd6d933629ff0ac02e&scope=&token_type=bearer
//        access_token=9e447e7d6803ffe00599591859528486a11cf684&scope=&token_type=bearer
        String url = "https://api.github.com/user";
        Map<String,String> headers = new HashMap<>();
        headers.put("accept", "application/json");
        headers.put("Authorization", "token " + token);
        Response response = OkHttpUtil.get(url, headers);
        String result = new String(response.body().bytes());
        System.out.println(result);
        return result;
    }
}
